package com.coachtam.ljgcapi.utils;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import java.util.*;


/**
 * HttpServletRequest帮助类
 * @author coach-tam
 */
public class RequestUtils {
	private static final Logger log = LoggerFactory
			.getLogger(RequestUtils.class);

	private static final String POST = "POST";
	private static final String UTF8 = "UTF-8";


	/**
	 * 获取访问者IP
	 *
	 * 在一般情况下使用Request.getRemoteAddr()即可，但是经过nginx等反向代理软件后，这个方法会失效。
	 *
	 * 本方法先从Header中获取X-Real-IP，如果不存在再从X-Forwarded-For获得第一个IP(用,分割)，
	 * 如果还不存在则调用Request .getRemoteAddr()。
	 *
	 * @param request
	 * @return
	 */
	public static String getIpAddr(ServerHttpRequest request) {
		String result = null;
		try {
			List<String> strings = request.getHeaders().get("X-Real-IP");

			if(CollectionUtils.isNotEmpty(strings))
			{
				String ip = strings.get(0);
				if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
					log.debug("此处为X-Real-IP请求,ip为{}:", ip);
					result = ip;
				}
			}

			List<String> ipList = request.getHeaders().get("X-Forwarded-For");
			if (CollectionUtils.isNotEmpty(ipList)) {
				String ip = ipList.get(0);

				if (!StringUtils.isBlank(ipList.get(0)) && !"unknown".equalsIgnoreCase(ip)) {
					log.debug("此处为X-Forwarded-For请求,ip为{}:", ip);
					// 多次反向代理后会有多个IP值，第一个为真实IP。
					int index = ip.indexOf(',');
					if (index != -1) {
						try {
							result = ip.substring(0, index);
						} catch (ArrayIndexOutOfBoundsException e) {
							log.error("获取访问者IP出错！截取的ip为:{}", ip);
							result = request.getRemoteAddress().getAddress().toString();
							if (result == null || StringUtils.isBlank(result)) {
								result = "0.0.0.0";
							}
						}
					} else {
						result = ip;
					}
				}
			}else {
				result = request.getRemoteAddress().getAddress().toString().replace("/","");
//				log.debug("此处为直接请求,ip为{}:", result);
			}


		} catch (Exception e) {
			log.error("getIpAddr error!");
			throw new RuntimeException(e);
		}

		return result;
	}


}
